package com.cloud.apis.message.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.cloud.apis.core.web.R;
import com.cloud.apis.message.pojo.form.DeleteMessageRefByIdForm;
import com.cloud.apis.message.pojo.form.SearchMessageByIdForm;
import com.cloud.apis.message.pojo.form.SearchMessageByPageForm;
import com.cloud.apis.message.pojo.form.UpdateUnreadMessageForm;
import com.cloud.apis.message.service.impl.MessageService;
import com.cloud.apis.message.task.MessageTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * 消息模块控制器
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/4/5
 */
@RestController
@RequestMapping("/message")
@Slf4j
@Api(tags = "消息相关API接口")
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private MessageTask messageTask;

    public MessageController(){
      log.info("【MessageController】");
    }
    @PostMapping("/searchMessageByPage")
    @ApiOperation("获取分页消息列表")
    public R searchMessageByPage(@Valid @RequestBody SearchMessageByPageForm form){
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        int page = form.getPage();
        int length = form.getLength();
        long start = (page-1)*length;
        List<HashMap> list = messageService.searchMessageByPage(userId, start, length);
        return R.ok().put("result",list);
    }

    @PostMapping("/searchMessageById")
    @ApiOperation("根据Id查询消息")
    public R searchMessageById(@Valid @RequestBody SearchMessageByIdForm form){
        return R.ok().put("result",messageService.searchMessageById(form.getId()));
    }

    @PostMapping("/updateUnreadMessage")
    @ApiOperation("未读消息更新为已读消息")
    public R updateUnreadMessage(@Valid @RequestBody UpdateUnreadMessageForm form){
        long rows = messageService.updateUnreadMessage(form.getId());
        return R.ok().put("result",rows==1?true:false);
    }

    @PostMapping("/deleteMessageRefById")
    @ApiOperation("删除消息")
    public R deleteMessageRefById(@Valid @RequestBody DeleteMessageRefByIdForm form){
        long rows = messageService.deleteMessageRefById(form.getId());
        return R.ok().put("result",rows==1?true:false);
    }

    @GetMapping("/refreshMessage")
    @ApiOperation("刷新用户的消息")
    public R refreshMessage(){
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        //异步接收消息
        messageTask.receiveAsync(userId+"");
        //查询接收了多少条消息
        long lastRows = messageService.searchLastCount(userId);
        //查询未读数据
        long unreadRows = messageService.searchUnreadCount(userId);
        return R.ok().put("lastRows",lastRows).put("unreadRows",unreadRows);
    }
}
